package com.lizardtech.djvu
{
	import flash.utils.ByteArray;
	
	
	public class IFFChunk
	{
		
		private var _djvufile:ByteArray;
		private var _name:String;
		private var _chunkDataOffsetStart:uint;
		private var _chunkDataOffsetEnd:uint;
		private var _chunkDataSize:uint;
		private var _position:uint;
		
		public function IFFChunk(djvufile:ByteArray, name:String, startOffset:uint, endOffset:uint) {
			_djvufile = djvufile;
			_name = name;
			_chunkDataOffsetStart = startOffset;
			_chunkDataOffsetEnd = endOffset;
			_chunkDataSize = _chunkDataOffsetEnd - _chunkDataOffsetStart;
			_position = _chunkDataOffsetStart;	
		}

		public function toIntArray():Array {
			var buffer:Array = new Array(_chunkDataSize);
			_djvufile.position = _chunkDataOffsetStart;
			for(var i:uint;_djvufile.position<_chunkDataOffsetEnd;i++) {
				buffer[i] = _djvufile.readByte();
			}
			return buffer;
		}
		
		public function read():int {
			// hack because the decoders are expecting one continuous data stream, not separate chunks
			if(_position >= _chunkDataOffsetEnd) {
				//trace("["+this.name+"] read past END of chunk: "+_position);
				return -1; 
			}

			_djvufile.position = _position;
			_position++;
			return 0xff & _djvufile.readUnsignedByte();
		}
		
		public function readShortInt():int {
			if(_position >= _chunkDataOffsetEnd) { 
				trace("["+this.name+"] read past END of chunk: "+_position);
				return -1; 
			}
			_djvufile.position = _position;
			_position += 2;
			return _djvufile.readShort();
		}
		
		public function readUInt16():uint {
			_djvufile.position = _position;
			_position += 2;
			return _djvufile.readUnsignedShort();
		}
		
		public function get name():String {
			return _name;
		}

		public function get position():uint {
			return _position;
		}
		
		public function set position(index:uint):void {
			_position = position;
		}

	}
}